package util

import (
	"archive/zip"
	"crypto/md5"
	"encoding/hex"
	"fmt"
	"io"
	"os"
	"time"
)

// ClearDir 清空目录
func ClearDir(dir string) error {
	if Exists(dir) {
		return os.RemoveAll(dir)
	}

	return nil
}

// GetFileMD5 获取文件的md5码
func GetFileMD5(filePath string) string {
	file, err := os.Open(filePath)
	defer func() {
		_ = file.Close()
	}()

	if err != nil {
		return ""
	}

	hash := md5.New()
	_, err = io.Copy(hash, file)
	if err != nil {
		return ""
	}

	return hex.EncodeToString(hash.Sum(nil))
}

// MkdirNX 创建文件目录
func MkdirNX(dirs ...string) error {
	var err error
	for _, dir := range dirs {
		_, err = os.Stat(dir)
		if err != nil && os.IsNotExist(err) {
			err = os.MkdirAll(dir, os.ModePerm)
			if err != nil {
				break
			}
		}
	}

	return err
}

// Exists 判断文件是否存在
func Exists(path string) bool {
	_, err := os.Stat(path)
	if err == nil {
		return true
	}

	if os.IsNotExist(err) {
		return false
	}

	return false
}

// CopyFile 复制文件
func CopyFile(targetFile, sourceFile string) error {
	<-time.After(1 * time.Second)

	source, err := os.Open(sourceFile)
	defer func() {
		_ = source.Close()
	}()

	if err != nil {
		return err
	}

	target, err := os.Create(targetFile)
	defer func() {
		_ = target.Close()
	}()

	if err != nil {
		return err
	}

	_, err = io.Copy(target, source)
	if err != nil {
		return err
	}

	<-time.After(1 * time.Second)

	return nil
}

func ZipFile(targetFile string, files ...string) error {
	fmt.Println("creating zip archive...")
	archive, err := os.Create(targetFile)
	if err != nil {
		panic(err)
	}
	defer archive.Close()
	zipWriter := zip.NewWriter(archive)

	if files != nil && len(files) > 0 {
		for i, f := range files {
			fmt.Println(fmt.Sprintf("opening %dst file...", i+1))
			f1, err := os.Open(f)
			if err != nil {
				return err
			}

			fmt.Println(fmt.Sprintf("writing %dst file to archive...", i+1))
			w1, err := zipWriter.Create(f1.Name())
			if err != nil {
				_ = f1.Close()
				return err
			}

			if _, err := io.Copy(w1, f1); err != nil {
				_ = f1.Close()
				return err
			}

			_ = f1.Close()
		}
	}

	fmt.Println("closing zip archive...")
	err = zipWriter.Close()
	if err != nil {
		return err
	}

	return nil
}
